<template>
  <div class="padding-page">
    <q-form @submit.prevent.stop="onSubmit" style="margin: 50px 20px 50px 20px">
      <!-- 提示信息 -->
      <div class="row justify-center q-gutter-x-md q-gutter-y-xs">
        <q-btn
          outline
          no-caps
          :ripple="false"
          v-for="example in searchExamples"
          :key="example.query"
          :label="example.query"
          @click="queryExample(example)"
        />
      </div>
      <div class="text-center">
        <q-input
          clearable
          outlined
          autofocus
          lazy-rules="ondemand"
          ref="inputRef"
          v-model="query"
          :label="t('queryForm.placeHolder')"
          :style="formStyles.input_margin"
          :hint="hint_message"
          :rules="inputRules"
        >
          <template v-if="!smallScreen" v-slot:after>
            <q-btn
              rounded
              fab
              unelevated
              @click="onSubmit"
              class="no-margin q-px-sm"
              type="submit"
              color="primary"
              size="lg"
              icon="search"
            />
          </template>
        </q-input>
      </div>
    </q-form>
    <!-- 搜索说明 -->
    <div class="row col-12">
      <div class="row col-12 text-center">
        <q-img
          class="row col-12"
          src="/assets/query/queryHelp.png"
          fit="scale-down"
          style="height: 250px"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useQuasar } from 'quasar';
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';

const { t } = useI18n({ useScope: 'global' });
const $q = useQuasar();
const smallScreen = computed(() => !$q.screen.gt.sm);
const router = useRouter();

// 表单的外观
const formStyles = computed(() => {
  return smallScreen.value
    ? {
        input_margin: { margin: '10px 5%' },
      }
    : {
        input_margin: { margin: '30px 15%' },
      };
});

// 轮播提示语
const index = ref(0);
const hint_message = ref(t('queryForm.example') + ' ' + 'rs1421085');
const message_list = ['rs2303208', 'ERAP2', 'chr5:96220000-96230000'];
let timer;
onMounted(() => {
  timer = setInterval(() => {
    if (index.value >= message_list.length) {
      index.value = 0;
    }
    hint_message.value =
      t('queryForm.example') + ' ' + message_list[index.value];
    index.value += 1;
  }, 3000);
});
onBeforeUnmount(() => {
  clearTimeout(timer);
});

// 查询示例
const searchExamples = [
  {
    query: 'rs7144811',
    bypos: 0,
    bytrait: 0,
  },
  {
    query: 'rs7143432,rs7144811',
    bypos: 0,
    bytrait: 0,
  },
  {
    query: 'chr16:70580000-70590000',
    bypos: 1,
    bytrait: 0,
  },
  {
    query: 'NPIPB15',
    bypos: 0,
    bytrait: 1,
  },
];

const queryExample = (params) => {
  router.push({
    name: 'ResultsPage',
    query: {
      query: params.query,
      bypos: params.bypos,
      bytrait: params.bytrait,
    },
  });
};

// 表单查询相关
const inputRef = ref(null);
// 表单字段
const query = ref('');
const bytrait = ref(0);
const bypos = ref(0);

// 验证规则
const inputRules = [
  (val) => {
    const containSpecial = (s: string) => {
      var containSpecial = RegExp(
        /[(\ )(\~)(\!)(\@)(\#)(\$)(\%)(\^)(\&)(\*)(\()(\))(\+)(\=)(\[)(\])(\{)(\})(\|)(\\)(\;)(\:)(\')(\")(\.)(\/)(\<)(\>)(\?)(\)]+/
      );
      return containSpecial.test(s);
    };
    // 空值
    if (val === null) {
      val = '';
    }
    const isEmpty = val === '';
    // 判断是不是rsid
    const matchedRsid = val.match(/^rs/);
    // 单个位置
    const matchedSinglePos = val.match(/^[chr]{0,}(\d{1,2}):(\d+)$/);
    const singlePosCorrect =
      matchedSinglePos !== null
        ? Number(matchedSinglePos[1]) > 0 &&
          Number(matchedSinglePos[1]) < 23 &&
          Number(matchedSinglePos[2]) > 0
        : null;
    // 两个位置
    const matchedDoublePos = val.match(/^[chr]{0,}(\d{1,2}):(\d+)-(\d+)$/);
    const doublePosCorrect =
      matchedDoublePos !== null
        ? Number(matchedDoublePos[1]) > 0 &&
          Number(matchedDoublePos[1]) < 23 &&
          Number(matchedDoublePos[2]) > 0 &&
          Number(matchedDoublePos[3]) > 0 &&
          Number(matchedDoublePos[3]) >= Number(matchedDoublePos[2])
        : null;

    if (isEmpty) {
      // 空值
      return t('queryForm.allertMessages.empty');
    } else if (matchedRsid) {
      // 输入rsid
      query.value = val;
      bytrait.value = 0;
      bypos.value = 0;
      return true;
    } else if (matchedSinglePos) {
      // 单位置
      if (singlePosCorrect) {
        query.value = `chr${matchedSinglePos[1]}:${matchedSinglePos[2]}-${matchedSinglePos[2]}`;
        bypos.value = 1;
        bytrait.value = 0;
        return true;
      } else {
        return t('queryForm.allertMessages.wrongPos');
      }
    } else if (matchedDoublePos) {
      // 双位置
      if (doublePosCorrect) {
        query.value = `chr${matchedDoublePos[1]}:${matchedDoublePos[2]}-${matchedDoublePos[3]}`;
        bypos.value = 1;
        bytrait.value = 0;
        return true;
      } else {
        return t('queryForm.allertMessages.wrongPos');
      }
    } else if (val.match(/^\d+/)) {
      // 数字开头的输入
      return t('queryForm.allertMessages.startWithNum');
    } else if (!containSpecial(val)) {
      // 包含特殊字符
      query.value = val;
      bytrait.value = 1;
      bypos.value = 0;
      return true;
    } else {
      return t('queryForm.allertMessages.startWithNum');
    }
  },
];
// 查询函数
const onSubmit = () => {
  inputRef.value.validate();
  if (!inputRef.value.hasError) {
    router.push({
      name: 'ResultsPage',
      query: {
        query: query.value,
        bypos: bypos.value,
        bytrait: bytrait.value,
      },
    });
  }
};
</script>
